<?php
/**
 * User: 苏翔
 * Date: 2024/8/16 14:07
 */

namespace App\Dao;

use App\HscoinConf;
use App\Model\HscoinBalanceModel;
use App\Model\HscoinBillModel;
use App\Model\PriceLogModel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Paginator\Paginator;

class PriceLogDao extends BaseDao
{

    #[Inject]
    protected PriceLogModel $model;


    function changeByHscoin(float $amount, $xid = 0)
    {
        $rt = [];
        $this->model->getConnection()->transaction(
            function () use (&$rt, $amount, $xid) {
                // get last fund_balance order by id desc
                $fund_balance =(float) $this->model->orderBy('id', 'desc')->lockForUpdate()->value('fund_balance');
                dev_log('last fund_balance', $fund_balance);
                // $fund_balance = $first['fund_balance'] ?? 0;
                $hscoin_balance = $amount;
                $price = $hscoin_balance > 0 ? $fund_balance / $hscoin_balance : 0;
                $data = compact('fund_balance', 'hscoin_balance', 'price', 'xid');
                $data['change_type'] = PriceLogModel::CHANGE_TYPE_HSCOIN;

                $id = $this->model->insertGetId($data);
                if ($id) {
                    $rt = $data;
                }
            }
        );
        return $rt;
    }

    /**
     * @param $amount
     * @param $xid
     * @return array
     * @throws \Throwable
     * @todo 优化 减少锁时间 insert into select from (slect sum( select )
     */
    function changeByFund($amount, $xid = 0)
    {
        $rt = [];
        $this->model->getConnection()->transaction(
            function () use (&$rt, $amount, $xid) {
                $first = $this->model->orderBy('id', 'desc')->lockForUpdate()->first();
                $hscoin_balance = $first['hscoin_balance'] ?? 0;
                $fund_balance = $amount;
                $price = $hscoin_balance > 0 ? $fund_balance / $hscoin_balance : 0;
                $data = compact('fund_balance', 'hscoin_balance', 'price', 'xid');
                $data['change_type'] = PriceLogModel::CHANGE_TYPE_FUND;

                $id = $this->model->insertGetId($data);
                if ($id) {
                    $rt = $data;
                }
            }
        );
        return $rt;
    }

    function getPrice()
    {
        return $this->model->orderBy('id', 'desc')->value('price');
    }

    function getPriceInfo()
    {

        return $this->model->orderBy('id', 'desc')->value('price');
    }
}
